package com.aaa.sbm.service.impl;

import com.aaa.sbm.common.ResultUtil;
import com.aaa.sbm.dao.UserDao;
import com.aaa.sbm.entity.User;
import com.aaa.sbm.service.UserService;
import com.aaa.sbm.util.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.UUID;

/**
 * @FileName: UserServiceImpl
 * @Description:
 * @Author: 王成林
 * @CreateTime: 2025/7/9 18:21
 * @Version: 1.0.0
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;
    @Resource
    private HttpSession session;

    @Override
    public Result checkUser(String username, String password) {
        try {
            log.info("开始验证用户登录，用户名：{}", username);
            
            User user = new User();
            user.setUser_name(username);
            List<User> userList = userDao.queryAllByLimit(user);
            
            if(!CollectionUtils.isEmpty(userList)){
                User userInfo = userList.get(0);
                String salt = userInfo.getSalt();
                String passwordDb = userInfo.getPassword();
                
                Sha512Hash sha512Hash = new Sha512Hash(password, salt, 1024);
                String passwordSHA = sha512Hash.toString();
                
                if(passwordDb.equals(passwordSHA)){
                    session.setAttribute("userinfo", userInfo);
                    log.info("用户登录成功：{}", username);
                    return ResultUtil.success("登录成功");
                }
            }
            
            log.warn("用户登录失败：{}", username);
            return ResultUtil.fail("用户名或密码错误");
        } catch (Exception e) {
            log.error("登录验证过程发生错误", e);
            return ResultUtil.fail("登录失败：" + e.getMessage());
        }
    }

    @Override
    public Result logout() {
        session.removeAttribute("userinfo");
        return ResultUtil.success("注销成功");
    }

    @Override
    public Result register(User user) {
        try {
            log.info("开始注册用户，用户信息：{}", user);
            
            // 1. 验证用户名是否已存在
            User queryUser = new User();
            queryUser.setUser_name(user.getUser_name());
            List<User> existingUsers = userDao.queryAllByLimit(queryUser);
            if (!CollectionUtils.isEmpty(existingUsers)) {
                log.warn("用户名已存在：{}", user.getUser_name());
                return ResultUtil.fail("用户名已存在");
            }

            // 2. 生成盐值
            String salt = UUID.randomUUID().toString().replace("-", "");
            user.setSalt(salt);

            // 3. 使用盐值加密密码
            Sha512Hash sha512Hash = new Sha512Hash(user.getPassword(), salt, 1024);
            user.setPassword(sha512Hash.toString());

            // 4. 设置用户状态
            user.setStatus("0");    // 0-正常
            user.setDel_flag("0");  // 0-未删除

            // 5. 保存用户信息
            log.info("准备保存用户信息：{}", user);
            int result = userDao.insert(user);
            if (result > 0) {
                log.info("用户注册成功，用户名：{}", user.getUser_name());
                return ResultUtil.success("注册成功");
            } else {
                log.error("用户注册失败，插入数据返回0");
                return ResultUtil.fail("注册失败，请稍后重试");
            }
        } catch (Exception e) {
            log.error("注册失败", e);
            return ResultUtil.fail("注册失败：" + e.getMessage());
        }
    }

    @Override
    public Result queryUserList(User user, Integer pageNum, Integer pageSize) {
        try {
            PageHelper.startPage(pageNum, pageSize);
            List<User> list = userDao.selectUserList(user);
            PageInfo<User> pageInfo = new PageInfo<>(list);
            return ResultUtil.success(pageInfo);
        } catch (Exception e) {
            log.error("查询用户列表失败", e);
            return ResultUtil.fail("查询失败：" + e.getMessage());
        }
    }
}
